package com.example.ecas.service.impl;

import com.example.ecas.persistence.AbstractsMapper;
import com.example.ecas.persistence.CaseMapper;
import com.example.ecas.pojo.Abstracts;
import com.example.ecas.pojo.Case;
import com.example.ecas.service.AbstractsService;
import com.example.ecas.utils.PythonExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class AbstractsServiceImpl implements AbstractsService {

    final static String pythonPath = "./ecas/src/main/python/sumy_filter.py";

    @Autowired
    AbstractsMapper abstractsMapper;

    @Autowired
    CaseMapper caseMapper;

    @Override
    public String getCaseAbstracts(int caseId) {
        Case _case = caseMapper.getCase(caseId);
        if (_case == null) {
            return null;
        }
        Abstracts abstracts = abstractsMapper.getAbstract(caseId);
        if (abstracts != null) {
            return  abstracts.getContent();
        }
        StringBuilder text = new StringBuilder();
        text.append(_case.getMain()!=null ? _case.getMain() : "");
        text.append(_case.getPresents()!=null ? _case.getPresents() : "");
        text.append(_case.getHistory()!=null ? _case.getHistory() : "");
        List<String> result;
        try {
            result = PythonExecutor.execPythonFile(pythonPath, text.toString().replace("\n", "").replace("\r",""));
        } catch (Exception e) {
            return null;
        }
        if (result.isEmpty()) {
            return null;
        }
        abstracts = new Abstracts();
        abstracts.setCaseId(caseId);
        abstracts.setContent(result.get(0));
        abstractsMapper.addAbstracts(abstracts);
        return result.get(0);
    }

}
